package net.xin.action;

import java.io.File;
import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import net.xin.model.Album;
import net.xin.model.User;
import net.xin.servlet.AlbumServlet;
import net.xin.servlet.UserServlet;

public class AlbumAction {
	private Album album;	//将照片的信息存入数据库中
	private File myfile;	//上传的文件
	private String myfileFileName;	//文件的名称
	private String myfileContentType;	//文件的类型
	private AlbumServlet albumServlet;	//因为要存入数据库，所以还需要注入albumServlet--调用DAO
	private UserServlet userServlet;
	public Album getAlbum() {
		return album;
	}
	public void setAlbum(Album album) {
		this.album = album;
	}
	public File getMyfile() {
		return myfile;
	}
	public void setMyfile(File myfile) {
		this.myfile = myfile;
	}
	public String getMyfileFileName() {
		return myfileFileName;
	}
	public void setMyfileFileName(String myfileFileName) {
		this.myfileFileName = myfileFileName;
	}
	public String getMyfileContentType() {
		return myfileContentType;
	}
	public void setMyfileContentType(String myfileContentType) {
		this.myfileContentType = myfileContentType;
	}
	public AlbumServlet getAlbumServlet() {
		return albumServlet;
	}
	@Resource
	public void setAlbumServlet(AlbumServlet albumServlet) {
		this.albumServlet = albumServlet;
	}
	
	public UserServlet getUserServlet() {
		return userServlet;
	}
	@Resource
	public void setUserServlet(UserServlet userServlet) {
		this.userServlet = userServlet;
	}
	public String upload() throws IOException {
		String realpath=ServletActionContext.getServletContext().getRealPath("/images");
		if(myfile!=null) {
			File savefile=new File(new File(realpath),myfileFileName);
			if(savefile.getParentFile().exists()) {
				savefile.getParentFile().mkdirs();
				FileUtils.copyFile(myfile, savefile);
				System.out.println("..........."+savefile);
			}
		}
		HttpServletRequest res=ServletActionContext.getRequest();
		album.setCover(res.getContextPath()+"/images/"+myfileFileName);
		User user=(User) ServletActionContext.getContext().getSession().get("USER");
		user=userServlet.get(user);
		System.out.println("............................"+user.getId());
		album.setUser(user);
		albumServlet.add(album);
		return "album";
	}
}
